var base = null
var utils = null
var azurCtrl = null
var server = null
func _ready():
	pass
func _init():
	call_deferred("omgInit")
	pass
func _connect():
	pass

func omgInit():
	if globalData.infoDs.has("g_azurlaneBase"):
		base = globalData.infoDs["g_azurlaneBase"]
	if base != null:
		#初始化
		utils = globalData.infoDs["g_azurlaneUtils"]
		server = globalData.infoDs["g_azurlaneServer"]
		azurCtrl = globalData.infoDs["g_azurlane"]
		azurCtrl.connect("resetData", self, "resetData")
		azurCtrl.connect("onLoadGame",self,"loadGame")
		base.connect("onSaveGame",self,"onSaveGame")

func loadGame():
	var tmp = base.getData("research", {})
	stage = tmp.get("stage")

func onSaveGame():
	var tmp = {}
	tmp["stage"] = stage
	base.setData("research", tmp)
		
func resetData():
	window = null
	stage = 0

var window
var rCha
var merchant

var stage:int = 0
var stageDescs = [
	["科研舰娘已经2级，玩家点击下方按钮提交100个魔方", "科研舰娘进行技能学习"],
	["科研舰娘已经3级，玩家点击下方按钮提交6个布里","科研舰娘进行技能学习"],
	["科研舰娘已经4级，玩家点击下方按钮提交3件任意装备(装备需放小卖部)","科研舰娘进行技能学习"],
	["玩家点击下方按钮提交300金币","科研舰娘进行属性强化"],
	["玩家点击下方按钮提交1个任意3级舰娘(会自动提交备战栏左数第一个)","科研舰娘进行属性强化"]
]

var helpTxt = """
玩家花费200金可以进行科研舰娘的抽取，一局只能抽一次，抽取后即可获得一个*1级*的对应科研舰娘
获得科研舰娘后，开启科研面板进行研发
研发共分为5个阶段，满足条件后点击下方的研发按钮即可进行当前阶段研发
"""

var contextTemp = "[center][b][color=#BDB76B]{name} - {stage}[/color][/b][/center]\n[color=#DC143C]条件[/color]：[color=#33ff33]{require}[/color]\n[color=#DC143C]奖励[/color]：\n[color=#33ff33]{award}[/color]"

func showHelp():
	utils.openHelpWindow(helpTxt)

func show():
	if not is_instance_valid(window) or not window is WindowDialog:
		window = utils.createWindowDialog(sys.main.get_node("ui"), "科研系统", Vector2(700, 400))

		utils.createItemButton(window, self, "说明", "showHelp", [], Vector2(600, 30))	

		var startBtn = utils.createItemButton(window, self, "开始研发", "startResearch", [], Vector2(300, 200))	
		startBtn.name = "startBtn"

		var context = utils.createRichTextLabel("", window, Vector2(530, 400), Vector2(100, 60))
		context.name = "context"

		var reBtn = utils.createItemButton(window, self, "研发", "doResearch", [], Vector2(350, 300))	
		reBtn.name = "reBtn"

	var startBtn = window.get_node("startBtn")
	var context = window.get_node("context")
	var reBtn = window.get_node("reBtn")
	if stage == 0:
		startBtn.show()
		context.hide()
		reBtn.hide()
	else:
		refreshContext()
		startBtn.hide()
		reBtn.show()

	if stage > 5:
		startBtn.hide()
		context.hide()
		reBtn.hide()

	window.popup_centered()	

func doResearch():
	if stage == 1:
		if azurCtrl.mf < 100:
			sys.newBaseMsg("警告", "研发失败：魔方不足！")
			return
		if rCha.lv < 2:
			sys.newBaseMsg("警告", "研发失败：科研舰娘等级不足！")
			return
		azurCtrl.changeMF(-100)
		rCha.showChoiceSkill(1)
	if stage == 2:
		if azurCtrl.buli < 6:
			sys.newBaseMsg("警告", "研发失败：布里不足！")
			return
		if rCha.lv < 3:
			sys.newBaseMsg("警告", "研发失败：科研舰娘等级不足！")
			return
		azurCtrl.changeBuli(-6)
		rCha.showChoiceSkill(2)
	if stage == 3:
		if merchant == null or not merchant is Chara:
			checkRcha()
		if merchant.items.size() < 3:
			sys.newBaseMsg("警告", "研发失败：装备不足，请将3件装备放置于小卖部！")
			return
		if rCha.lv < 4:
			sys.newBaseMsg("警告", "研发失败：科研舰娘等级不足！")
			return
		var its = []
		for i in range(3):
			its.append(merchant.items[i])
		for i in its:
			merchant.delItem(i)
			i.delSelf()

		rCha.showChoiceSkill(3)
	if stage == 4:
		if sys.main.player.gold < 300:
			sys.newBaseMsg("警告", "研发失败：金币不足！")
			return
		sys.main.player.plusGold(-300)
		showChoiceAttr()
	if stage == 5:
		var cha = null
		for i in utils.getReadyChas():
			if i.lv == 3:
				cha = i
				break
		if cha == null:
			sys.newBaseMsg("警告", "研发失败：没检测到待献祭角色！")
			return
		cha.deleteSelf()
		showChoiceAttr()
	stage += 1
	if stage > 5:
		self.window.get_node("startBtn").hide()
		self.window.get_node("context").hide()
		self.window.get_node("reBtn").hide()
	window.hide()	

func startResearch():
	if sys.main.player.gold < 200:
		sys.newBaseMsg("警告", "研发失败：金币不足！(需要200)")
		return

	var window = utils.createWindowDialog(sys.main.get_node("ui"), "科研舰娘", Vector2(840, 400))
	window.popup_exclusive = true
	window.get_close_button().hide()

	utils.createRichTextLabel("请选择要研发的舰娘", window, Vector2(200, 50), Vector2(30, 30))
	var grid = utils.createGridContainer(window, 5, Vector2(50, 100))
	utils.newChaBt(grid, "aijier-4")
	utils.newChaBt(grid, "ankeleiqi-4")
	utils.newChaBt(grid, "bailong-4")
	utils.newChaBt(grid, "buleisite-4")
	utils.newChaBt(grid, "pulimaosi-4")

	utils.createItemButton(grid, self, "选择", "doChoiceChara", ["aijier-1", window])
	utils.createItemButton(grid, self, "选择", "doChoiceChara", ["ankeleiqi-1", window])
	utils.createItemButton(grid, self, "选择", "doChoiceChara", ["bailong-1", window])
	utils.createItemButton(grid, self, "选择", "doChoiceChara", ["buleisite-1", window])
	utils.createItemButton(grid, self, "选择", "doChoiceChara", ["pulimaosi-1", window])
	window.popup_centered()

func doChoiceChara(id, window):
	rCha = utils.newChara(id)
	sys.main.player.addCha(rCha)
	window.queue_free()
	self.window.get_node("startBtn").hide()
	self.window.get_node("context").show()
	self.window.get_node("reBtn").show()
	stage = 1
	refreshContext()
	sys.main.player.plusGold(-200)

func refreshContext():
	if stage == 0:return
	if rCha == null:
		checkRcha()
	var context = window.get_node("context")
	context.bbcode_text = contextTemp.format({
		"name":rCha.chaName.rsplit("」")[1],
		"stage":getStageTxt(),
		"require":stageDescs[stage-1][0],
		"award":stageDescs[stage-1][1]
	})

func getStageTxt():
	match stage:
		0:return "尚未开始"
		1:return "第一阶段"
		2:return "第二阶段"
		3:return "第三阶段"
		4:return "第四阶段"
		5:return "第五阶段"

func checkRcha():
	var chas = utils.getAllChas(2)
	chas += utils.getReadyChas()
	for i in chas:
		if i.get("researchTag") != null:
			rCha = i
		if i.id == "merchant":
			merchant = i
	
var attrConfig = [
	{"name":"炮击", "val":150, "attr":"atk", "pct":false},
	{"name":"雷击", "val":150, "attr":"mgiAtk", "pct":false},
	{"name":"航空", "val":150, "attr":"air", "pct":false},
	{"name":"血量", "val":0.3, "attr":"maxHpL", "pct":true},
	{"name":"装甲", "val":80, "attr":"def", "pct":false},
	{"name":"机动", "val":80, "attr":"dod", "pct":false},
	{"name":"冷却", "val":0.4, "attr":"cd", "pct":true},
	{"name":"射速", "val":0.5, "attr":"spd", "pct":true},
	{"name":"暴击", "val":0.4, "attr":"cri", "pct":true},
]
var airExclude = ["atk", "mgiAtk", "spd"]
func showChoiceAttr():
	var window = utils.createWindowDialog(sys.main.get_node("ui"), "属性强化", Vector2(500, 400))
	window.popup_exclusive = true
	window.get_close_button().hide()
	window.name = "attrWindow"

	utils.createRichTextLabel("请选择要强化的属性", window, Vector2(200, 50), Vector2(30, 30))
	var grid = utils.createGridContainer(window, 2, Vector2(50, 100))

	var opts = []
	for i in range(3):
		var opt = sys.rndListItem(attrConfig)
		while opts.has(opt) or rCha.prefer == "air" and airExclude.has(opt.attr) or rCha.prefer != "air" and opt.attr == "air":
			opt = sys.rndListItem(attrConfig)
		opts.append(opt)

	for i in opts:
		var attr = str(i.val)
		if i.pct:
			attr = str(i.val*100) + "%"
		utils.createRichTextLabel("[color=#BDB76B]{name}[/color] [color=#DC143C]{attr}[/color]".format({"name":i.name,"attr":attr}), grid, Vector2(300, 50))
		utils.createItemButton(grid, self, "选择", "doSelectAttr", [i, window])
	window.popup_centered()

func doSelectAttr(opt, window):
	window.queue_free()
	rCha.attEx.set(opt.attr, rCha.attEx.get(opt.attr) + opt.val)
	rCha.upAtt()
